//
//  UMengManager.swift
//  
//
//  Created by gy on 2022/3/24.
//

import Foundation
import UIKit

// 友盟
private let kUMAppKey = "6599243895b14f599d11571d"
private let kWXAppKey = "wx9b5164bcef8ebd74"
private let kWXAppSecret = "04387c26887b04225e0b9f89fa8ca4bd"

let kUMengManager = UMengManager.shared

class UMengManager {
    static let shared = UMengManager()
    // 是否配置了友盟
    private(set) var isInitUm = false
}

// MARK: ---- UM init
extension UMengManager {
    
    // 基础组件
    func initUMCommon() {
                
        MobClick.setAutoPageEnabled(false)
        UMConfigure.initWithAppkey(kUMAppKey, channel: "App Store")
        //配置微信平台的Universal Links
        UMSocialGlobal.shareInstance().universalLinkDic = [UMSocialPlatformType.wechatSession.rawValue: "https://doc.jc-tour.net"]
        UMCrashConfigure.setCrashCBBlock { () -> String? in
            return "发生了我们测试的Crash"
        }
          
        UMConfigure.getUmengZID()
    }
    // 分享组件
    func initUMSocial() {
        /* 设置微信的appKey和appSecret */
        UMSocialManager.default().setPlaform(.wechatSession, appKey: kWXAppKey, appSecret: kWXAppSecret, redirectURL: "http://mobile.umeng.com/social")
        isInitUm = true
    }
    
}

// MARK: ---- UM Login
extension UMengManager {
    
    func um_login(platformType: UMSocialPlatformType, currentVC: UIViewController, holder: @escaping UMSocialRequestCompletionHandler) {
        
        UMSocialManager.default().getUserInfo(with: platformType, currentViewController: currentVC) { result, error in
            holder(result, error)
        }
        
    }
    
}

// MARK: ---- UM Share
extension UMengManager {
    
    // 分享文字
    func umTextShare(text: String, platformType: UMSocialPlatformType) {
        
        guard let currentVC = Utils.getTopVC() else { return }
        
        let messageObject = UMSocialMessageObject()
        messageObject.text = text

        UMSocialManager.default().share(to: platformType, messageObject: messageObject, currentViewController: currentVC) { (data, error) in
            if error != nil {
                MYLog("************分享失败 \(error)*********")
                MYLog(error.description)
            }else{
                if data is UMSocialShareResponse {
                    let resp = data as? UMSocialShareResponse
                    // 分享结果消息
                    if let message = resp?.message {
                        MYLog("************分享成功 \(message)*********")
                    }
                } else {
                    if let data = data {
                        MYLog("response data is \(data)")
                    }
                }
            }
            
        }
    }
    
    // 链接分享
    func umWebPageShare(url: String, title: String, descr: String? = nil, icon: Any, platformType: UMSocialPlatformType, currentVC: UIViewController) {
        
        let webObject = UMShareWebpageObject()
        webObject.webpageUrl = url
        webObject.title = title
        if let descr = descr {
            webObject.descr = descr
        }
        webObject.thumbImage =  icon
        let messageObject = UMSocialMessageObject.init(mediaObject: webObject)
        
//        if #available(iOS 15.0, *) {
//            Task(priority: .low) {
//                let result = try await UMSocialManager.default().share(to: platformType, messageObject: messageObject, currentViewController: currentVC)
//                MYLog(result)
//            }
//        } else {
            UMSocialManager.default().share(to: platformType, messageObject: messageObject, currentViewController: currentVC) { (data, error) in
                if error != nil {
                    MYLog("************分享失败 \(error!)*********")
                    MYLog(error.description)
                }else{
                    if data is UMSocialShareResponse {
                        let resp = data as? UMSocialShareResponse
                        // 分享结果消息
                        if let message = resp?.message {
                            MYLog("************分享成功 \(message)*********")
                        }
                    } else {
                        if let data = data {
                            MYLog("response data is \(data)")
                        }
                    }
                }
                
            }
//        }
        
    }
    
    // 图片分享
    func umPictureShare(picture: Any, platformType: UMSocialPlatformType, currentVC: UIViewController) {
        
        let webObject = UMShareImageObject()
        webObject.shareImage = picture
        let messageObject = UMSocialMessageObject.init(mediaObject: webObject)
        
//        if #available(iOS 15.0, *) {
//            Task(priority: .low) {
//                let result = try await UMSocialManager.default().share(to: platformType, messageObject: messageObject, currentViewController: currentVC)
//                MYLog(result)
//            }
//        } else {
            UMSocialManager.default().share(to: platformType, messageObject: messageObject, currentViewController: currentVC) { (data, error) in
                if error != nil {
                    MYLog("************分享失败 \(error!)*********")
                    MYLog(error.description)
                }else{
                    if data is UMSocialShareResponse {
                        let resp = data as? UMSocialShareResponse
                        // 分享结果消息
                        if let message = resp?.message {
                            MYLog("************分享成功 \(message)*********")
                        }
                    } else {
                        if let data = data {
                            MYLog("response data is \(data)")
                        }
                    }
                }
                
            }
//        }
        
    }
    
    // 小程序分享
    func umMiniProgramShare(userName: String, path: String, webpageUrl: String, icon: UIImage, platformType: UMSocialPlatformType, currentVC: UIViewController) {
        
        let messageObject = UMSocialMessageObject()
        let shareObject = UMShareMiniProgramObject()
        shareObject.webpageUrl = webpageUrl
        shareObject.userName = userName
        shareObject.path = path
        if let pngData = icon.pngData() {
            shareObject.hdImageData = pngData
        }
        shareObject.miniProgramType = .release

        messageObject.shareObject = shareObject

//        if #available(iOS 15.0, *) {
//            Task(priority: .low) {
//                let result = try await UMSocialManager.default().share(to: platformType, messageObject: messageObject, currentViewController: currentVC)
//                MYLog(result)
//            }
//        } else {
            UMSocialManager.default().share(to: platformType, messageObject: messageObject, currentViewController: currentVC) { (data, error) in
                if error != nil {
                    MYLog("************分享失败 \(error!)*********")
                    MYLog(error.description)
                }else{
                    if data is UMSocialShareResponse {
                        let resp = data as? UMSocialShareResponse
                        // 分享结果消息
                        if let message = resp?.message {
                            MYLog("************分享成功 \(message)*********")
                        }
                    } else {
                        if let data = data {
                            MYLog("response data is \(data)")
                        }
                    }
                }
                
            }
//        }
        
    }
    
}

// MARK: ---- UM 统计
extension UMengManager {
    
    /// record
    func um_statisticsEvent(eventId: String, label: String? = nil, attributes: [String:Any]? = nil) {

        // umeng
        if let tag = label {
            MobClick.event(eventId, label: tag)
        } else if let value = attributes {
            MobClick.event(eventId, attributes: value)
        } else {
            MobClick.event(eventId)
        }
        
    }
    
    /// 时长统计
    func um_statisticsEventStart(eventId: String) {
        
        // umeng
        MobClick.beginEvent(eventId)
        
    }
    func sum_tatisticsEventEnd(eventId: String) {
        
        // umeng
        MobClick.endEvent(eventId)
        
    }
    
}

